package io.github.annyylxyms.gyncache.core;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 *
 * @author Anny
 * @date 2024/12/31 15:14
 */
public class GynCacheDecoder extends ByteToMessageDecoder {
    //计数器(用于打标当前是第几次decoder)
    AtomicLong counter = new AtomicLong();

    /**
     * Netty 重写RedisDecoder解析协议
     * @param ctx 上下文
     * @param in 请求提交的数据二进制封装
     * @param out 往里填入的响应数据
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        System.out.println("decodeCount: " + counter.incrementAndGet());

        //读不到数据，直接返回
        if (in.readableBytes() <= 0) return;
        int count = in.readableBytes();
        int index = in.readerIndex();
        System.out.println("count:" + count + ",index:" + index);

        byte[] bytes = new byte[count];
        in.readBytes(bytes);
        String ret = new String(bytes);
        System.out.println("ret:" + ret);

        //把响应数据放入out，list里在流水线里就可以继续往下传了。
        out.add(ret);
    }
}
